package com.zecan.blog.job;

import com.zecan.blog.common.status.BlogCommonStatus;
import com.zecan.blog.controller.exception.BlogException;
import com.zecan.blog.dao.ArticleMapper;
import com.zecan.blog.utils.BlogConstant;
import com.zecan.blog.utils.RedisUtils;
import com.zecan.blog.utils.SpringUtils;
import com.zecan.blog.utils.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class UpdateArticleViewJob extends QuartzJobBean {
    private static final Logger log = LoggerFactory.getLogger(UpdateArticleViewJob.class);
    private RedisUtils redisUtils = (RedisUtils) SpringUtils.getBean(RedisUtils.class);
    private ArticleMapper articleMapper = (ArticleMapper)SpringUtils.getBean(ArticleMapper.class);

    public UpdateArticleViewJob() {

    }

    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        System.out.println("当前时间" + StringUtils.dateFormat(new Date()) + "开始执行更新文章浏览定时任务");
        Object savePoint = null;

        try {
            // 从redis中获取更新的数据集合
            Set<String> keys =  Objects.requireNonNull(redisUtils.getKeys(BlogConstant.BLOG_VIEW+ "*"));
            if (keys.size() == 0) {
                System.out.println("当前时间" + StringUtils.dateFormat(new Date()) + "没有需要更新的文章浏览");
                return;
            }

            List<Integer> ids = new ArrayList<>();
            // 获取对应的id
            keys.forEach((s) -> {
                ids.add(Integer.valueOf(s.split(":")[1]));
            });
            // 根据keys 获取对应的值
            List<Object> viewCount = this.redisUtils.multiGetStringKey(keys);
            List<Map<String, Object>> mapList = new ArrayList<>();

            // 对应文章id 与 数量的封装
            if (Objects.nonNull(viewCount)) {
                for(int i = 0; i < ids.size(); ++i) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", ids.get(i));
                    map.put("count", viewCount.get(i));
                    mapList.add(map);
                }
            }
        // 修改
            Integer integer = this.articleMapper.updateArticlesView(mapList);
            if (!integer.equals(ids.size())) {
                throw new BlogException(BlogCommonStatus.REQUEST_DATA_ERROR);
            }

            this.redisUtils.delKeys(keys);
        } catch (RuntimeException var9) {
            log.error("当前更新数据的结果不匹配" + var9.getMessage());
        }

        System.out.println("当前时间" + StringUtils.dateFormat(new Date()) + "更新文章浏览定时任务执行结束");
    }
}